import { cumulate, arrange, policyCompute } from "../../utils";
import dayjs from "dayjs";

const barOpacity = 0.9;

const generateSeriesData = ({ cumulateData, tags, template }) => {
  // console.log("generateSeriesData", template);
  if (!template || !cumulateData || cumulateData.length == 0) {
    return null;
  }

  let seriesData = [];
  let valTotal = Array(cumulateData.length).fill(0);

  template.series.forEach((series, seriesIndex) => {
    let seriesTarget = {
      name: series.name,
      data: [],
      remark: "series",
    };

    if (series.color && series.color != "") {
      seriesTarget.definedColor = series.color;
    }

    cumulateData.forEach((row, rowIndex) => {
      let val = 0;

      series.tags.forEach((tag) => {
        let tid = tags.indexOf(tag);
        if (tid > -1) {
          val += row[tid];
        }
      });

      seriesTarget.data.push({
        value: val,
        itemStyle: {
          opacity: val == 0 ? 0 : barOpacity,
        },
      });

      valTotal[rowIndex] += val;
    });

    seriesData.push(seriesTarget);
  });

  // 计算合计
  const totalData = valTotal.map((val) => ({ value: val }));
  const totalMax = Math.max(...valTotal);
  // console.log("totalMax", totalMax);
  seriesData.unshift({
    name: "合计",
    data: totalData,
    max: totalMax,
    remark: "total",
  });

  return seriesData;
};

export default function ({
  rawData,
  tags,
  begTime,
  dataInterval,
  dataStep,
  template,
}) {
  const cumulateData =
    !rawData || rawData.length == 0
      ? []
      : cumulate(rawData, dataInterval, dataStep);

  let startDayjs = dayjs(begTime);
  const momentData = Array.from({ length: cumulateData.length }, (v, k) =>
    startDayjs.add(k * dataInterval * 15, "minute")
  );

  if (dataInterval == 1) {
    cumulateData.splice(0, 14);
    momentData.splice(0, 14);
  } else if (dataInterval == 2) {
    cumulateData.splice(0, 5);
    momentData.splice(0, 5);
  }

  const seriesData = generateSeriesData({
    cumulateData,
    tags,
    template,
  });

  const max = seriesData.find((s) => s.remark == "total")?.max || 0;
  return {
    title: template?.title || "Unnamed Template",
    series: seriesData,
    max: max,
    raw: rawData,
    cumulated: cumulateData,
    moments: momentData,
  };
}
